import { EggLogger } from 'egg';
import { Inject, HTTPController, HTTPMethod, HTTPMethodEnum, Context, EggContext, Middleware, HTTPBody, HTTPQuery } from '@eggjs/tegg';
import { responseFormatter } from 'app/middleware/responseFormatter';
import { AddFactoryOptions, UpdateFactoryOptions } from 'typings/app/factory';
import { EggAppConfig } from 'typings/app';
import { toInt, removeUndefinedValues } from 'app/libs/utils';

@HTTPController({
  path: '/factory',
})
@Middleware(responseFormatter)
export class FactoryController {
  @Inject()
  logger: EggLogger;
  @Inject()
  config: EggAppConfig;

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/updateFactory',
  })
  async updateFactory(@Context() ctx: EggContext, @HTTPBody() factory: UpdateFactoryOptions) {
    await ctx.model.Factory.update(factory, {
      where: { id: factory.id },
    });
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.DELETE,
    path: '/deleteFactory',
  })
  async deleteFactory(@Context() ctx: EggContext, @HTTPQuery() id: number) {
    const factory = await ctx.model.Factory.findByPk(id);
    await factory.destroy();
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.POST,
    path: '/addFactory',
  })
  async addFactory(@Context() ctx: EggContext, @HTTPBody() factory: AddFactoryOptions) {
    const currFactory = await ctx.model.Factory.findOne({
      where: { name: factory.name },
    });
    if (currFactory) {
      ctx.throw({
        code: 1001,
        message: '添加失败，存在同名的工厂！',
      });
    }
    await ctx.model.Factory.create(factory);
    return {};
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getFactoryOptions',
  })
  async getFactoryOptions(@Context() ctx: EggContext) {
    return await ctx.model.Factory.findAll({
      attributes: [ 'id', 'name' ],
    });
  }

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getFactoryList',
  })
  async getFactoryList(@Context() ctx: EggContext) {
    const factoryQuery = ctx.query;
    const limit = toInt(factoryQuery?.limit || this.config.query.pageSize);
    const condition = removeUndefinedValues({
      id: factoryQuery?.id,
      name: factoryQuery?.name,
    });
    const list = await ctx.model.Factory.findAll({
      limit,
      offset: toInt(factoryQuery.page) * limit,
      where: condition,
    });
    const total = await ctx.model.Factory.count({
      where: condition,
    });
    return { list, total };
  }
}
